package com.nidu.demo.role.ability;

import cn.hutool.core.collection.CollUtil;
import com.alibaba.cola.exception.BizException;
import com.nidu.demo.common.constants.Constants;
import com.nidu.demo.common.enums.RoleCodeEnum;
import com.nidu.demo.common.enums.RoleTypeEnum;
import com.nidu.demo.common.exception.ErrorCodeConstants;
import com.nidu.demo.role.gateway.RoleGateway;
import com.nidu.demo.role.gateway.RoleMenuGateway;
import com.nidu.demo.role.model.Role;
import com.nidu.demo.user.gateway.UserRoleGateway;
import com.nidu.demo.user.model.UserRole;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collections;
import java.util.Set;
import java.util.Map;
import java.util.List;

@Component
@RequiredArgsConstructor
public class RoleDomainService {

    private final RoleGateway gateway;

    private final UserRoleGateway userRoleGateway;

    private final RoleMenuGateway roleMenuGateway;

    public void validateDuplicate(String code, Long excludeId) {
        // 检查编码是否重复
        Role role = gateway.getByCode(code);
        if (role != null) {
            if(excludeId == null){
                throw new BizException(ErrorCodeConstants.ROLE_CODE_DUPLICATE.getCode(),
                        ErrorCodeConstants.ROLE_CODE_DUPLICATE.getMessage());
            } else if(!excludeId.equals(role.getId())){
                throw new BizException(ErrorCodeConstants.ROLE_CODE_DUPLICATE.getCode(),
                        ErrorCodeConstants.ROLE_CODE_DUPLICATE.getMessage());
            }
        }
    }

    public void validateUserUse(Set<Long> roleIds){
        Map<Long, List<UserRole>> userRoleMap = userRoleGateway.getByRoleIds(roleIds);
        if (!CollUtil.isEmpty(userRoleMap)) {
            throw new BizException(ErrorCodeConstants.ROLE_HAS_USER.getCode(),
                    ErrorCodeConstants.ROLE_HAS_USER.getMessage());
        }
    }

    @Transactional
    public void deleteRole(Long roleId){
        // 1. 检查是否被用户绑定
        validateUserUse(Collections.singleton(roleId));

        // 2. 执行逻辑删除
        userRoleGateway.removeRoleUsers(roleId);
        roleMenuGateway.removeRoleMenus(roleId);
        gateway.deleteById(roleId);
    }

    @Transactional
    public void deleteRoles(Set<Long> roleIds) {
        // 1. 检查是否被用户绑定
        validateUserUse(roleIds);

        // 2. 删除角色-菜单关联
        userRoleGateway.removeRolesUsers(roleIds);
        roleMenuGateway.removeRolesMenus(roleIds);

        // 3. 执行逻辑删除
        gateway.deleteByIds(roleIds);
    }

}